package main.sql;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @className: Controller
 * @package: main
 * @author: qiufeng@hsyuntai.com
 * @date: 2019/5/16 14:25
 * @copyright: 版权归 HSYUNTAI 所有
 */
@RestController
public class Controller {

    private static int i = 0;

    private ReentrantLock lock = new ReentrantLock();

    @Resource
    private DemoDao demoDao;

    @GetMapping("/demo")
    @ResponseBody
    public String demo() throws Exception {
        System.out.println("第 " + i + " 个线程，demo enter : " + Thread.currentThread().getId());
        return demoDao.get();
    }

    @GetMapping("/hello")
    @ResponseBody
    public String hello() throws Exception {
        System.out.println("第 " + i + " 个线程，hello enter : " + Thread.currentThread().getId());
        try {
                lock.lock();
                int m = 0;
                for (int j = 0; j < Integer.MAX_VALUE * Integer.MAX_VALUE * Integer.MAX_VALUE * Integer.MAX_VALUE * Integer.MAX_VALUE; j ++) {
                    m = m + i + j;
                }
                System.out.println("第 " + i + " 个线程，hello success : " + Thread.currentThread().getId());
                return "success";
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("第 " + i + " 个线程，hello failed : " + Thread.currentThread().getId());
                return "failed";
            } finally {
                lock.unlock();
        }
    }

    @GetMapping("/world")
    @ResponseBody
    public String world() throws Exception {
        System.out.println("第 " + i + " 个线程，world enter : " + Thread.currentThread().getId());
        try {
            List<String> list = new ArrayList<>();
            for (int j = 0; j < Integer.MAX_VALUE; j ++) {
                list.add("this is memory test " + i + j);
            }
            System.out.println("第 " + i + " 个线程，world success : " + Thread.currentThread().getId());
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("第 " + i + " 个线程，world failed : " + Thread.currentThread().getId());
            return "failed";
        }
    }


}
